from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosDining, collectionDiningList
from app.globals.uuidTool import getuuId
from app.db.dbUserManage import getUserNameByuserId
from app.globals.publicMethod import globalGetNowTime, globalTimeToString


def createDining(diningName, diningDesc, menuInfo, userId):
    '''
    创建餐厅
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'diningName': diningName}
        collection = mg_client[dbSynPosDining][collectionDiningList]
        res = collection.find_one(cond)
        # 如果该餐厅存在
        if res is not None:
            return False
            
        diningNo = getuuId()
        now = globalGetNowTime()
        username = getUserNameByuserId(userId)
        data = {
            'diningNo': diningNo,
            'diningName': diningName,
            'diningDesc': diningDesc,
            'createTime': now,
            'updateTime': now,
            'creatorUserName': username,
            'editorUserName': username,
            'menuList' : menuInfo
        }
        collection.insert_one(data)

        return diningNo
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def editDining(diningNo, diningName, diningDesc, menuInfo, userId):
    '''
    编辑餐厅
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDining][collectionDiningList]
        # 判断重名
        cond = {'diningName': diningName}
        res = collection.find_one(cond)
        #如果新的餐厅名存在
        if res is not None and res.get('diningNo') != diningNo:
            return False

        cond = {'diningNo': diningNo}
        now = globalGetNowTime()
        username = getUserNameByuserId(userId)
        
        return collection.find_one_and_update(cond, 
                    {'$set': 
                        {
                            'diningName': diningName,
                            'updateTime': now,
                            "editorUserName": username,
                            'diningDesc': diningDesc,
                            "menuList": menuInfo
                        }
                    })
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def delDining(diningNo):
    '''
    删除餐厅
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'diningNo': diningNo}
        collection = mg_client[dbSynPosDining][collectionDiningList]
        res = collection.find_one({'diningNo': diningNo})
        if res is None:
           return None

        stallList = res.get('stallList')
        if stallList is not None and len(stallList) > 0:
            # 有档口的餐厅不允许删除
            return False

        return collection.find_one_and_delete(cond)
    except Exception as e:
        raise ErrMongoClient.data(str(e))